package controller

import (
	"gin-blog/app/model"
	"github.com/cihub/seelog"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func Login(ctx *gin.Context) {
	if CheckAuth(ctx) {
		seelog.Warn("重复登录了~")
		ctx.JSON(200, gin.H{
			"message": "repeat login",
		})
	} else {
		username := ctx.Query("username")
		password := ctx.Query("password")

		auth := model.FetchOne(username)
		if auth.Password != password {
			ctx.JSON(401, gin.H{
				"message": "帐号密码错误",
			})
		} else {
			seelog.Info("用户登录")
			
			session := sessions.Default(ctx)
			session.Set("username", username)
			session.Save()
			
			seelog.Trace(auth)
			//s := session.Get("username")
			//fmt.Println(s)
			ctx.JSON(200, gin.H{
				"message": "login",
			})
		}
	}
}

func Logout(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Clear()
	session.Save()
	
	ctx.JSON(200, gin.H{
		"message": "logout success",
	})
}

func CheckAuth(ctx *gin.Context) bool {
	session := sessions.Default(ctx)
	username := session.Get("username")
	//fmt.Println(username)
	if username != nil {
		return true
	}

	return false
}
